package com.example.modlemain.ui.main

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.util.TypedValue
import android.widget.TextView
import com.example.modlemain.ui.main.custom.RoundBackgroundSpan

object SpanUtils {
    fun dpToPx(context: Context, dp: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp,
            context.resources.displayMetrics
        )
    }

    fun applyRoundBackground(
        textView: TextView,
        targetText: String,
        bgColor: Int,
        textColor: Int = Color.WHITE,
        cornerRadiusDp: Float = 4f,
        paddingDp: Float = 4f
    ) {
        val spannable = SpannableString(textView.text)
        val start = textView.text.indexOf(targetText)
        if (start >= 0) {
            val end = start + targetText.length
            spannable.setSpan(
                RoundBackgroundSpan(
                    bgColor,
                    textColor,
                    dpToPx(textView.context, cornerRadiusDp),
                    dpToPx(textView.context, paddingDp)
                ),
                start,
                end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            textView.text = spannable
        }
    }
}
